/**查找分页控件 -> 请求下一页 -> 增删元素 -> 加载在页面 */
async function loadNextPage() {
  let [lastNrPage] = [...document.getElementsByClassName('page_chapter')].slice(-1)
  let url = lastNrPage.querySelector('li:nth-child(3) a').href

  const response = await fetch(url)

  let host = window.location.host
  let isUseGbk = [].includes(host)

  const decoder = new TextDecoder(isUseGbk ? 'gbk' : 'utf8')
  const html = decoder.decode(await response.arrayBuffer())
  let div = document.createElement('div')
  div.innerHTML = html

  let alink = document.createElement('a')
  alink.href = url
  alink.innerText = '本页'
  let li = document.createElement('li')
  li.appendChild(alink)
  let pageDom = div.querySelectorAll('.page_chapter ul')
  pageDom.forEach((item) => {
    item.insertBefore(li.cloneNode(true), item.children[3])
    item.removeChild(item.children[4])
  })

  cleanPage(div)

  let [lastContent] = [...document.getElementsByClassName('content')].slice(-1)
  lastContent.parentNode.appendChild(div)
  return { div, url }
}

/**从页面获取书名 */
function getBookName() {
  let dom = document.querySelector('#info h1')
  if (dom) {
    return dom.innerText
  }

  dom = document.querySelector('#book .p a:nth-of-type(2)')
  if (!dom) return ''
  return dom.innerText
}

/**_addObserver传入targetSelector、chapterTitleSelector*/
function addObserver(dom = document, url = location.href) {
  _addObserver('.content', '.content h1', dom, url)
}

/**包装cleanPage方法 */
function cleanPage(context = document) {
  let selectorArr = ['.ywtop', '.header', '.nav', '.path', '.page_chapter:first-of-type', '.content .linkk', '#footer']
  let host = window.location.host
  if (['www.6sgl.com'].includes(host)) {
    let dom = context.querySelector('.ywtop')
    if (dom) {
      let parent = dom.parentNode
      let divDom = parent.querySelector('div[style="text-align: center;"]')
      divDom && parent.removeChild(divDom)
    }
  }
  $chromePlugin.cleanPage(context, selectorArr)
}

$chromePlugin.loadQueueFn.push(cleanPage)
